package com.skydoves.chatgpt.core.data.di

import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import com.skydoves.chatgpt.core.data.repository.AppUserRepository
import com.skydoves.chatgpt.core.data.repository.AppUserRepositoryImpl
import com.skydoves.chatgpt.core.network.service.UserService
import com.squareup.moshi.Moshi
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import javax.inject.Singleton

val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "user_prefs")
private val UID_KEY = stringPreferencesKey("uid")


@Module
@InstallIn(SingletonComponent::class)
object AppModule {

  // 提供 ApplicationContext
  @Provides
  @Singleton
  fun provideContext(@ApplicationContext context: Context): Context {
    return context // 返回应用上下文
  }

  @Provides
  @Singleton
  fun provideMoshi(): Moshi {
    return Moshi.Builder().build() // 创建 Moshi 实例
  }

  @Provides
  @Singleton
  fun provideDataStore(@ApplicationContext applicationContext: Context): DataStore<Preferences> {
    return applicationContext.dataStore // 提供 DataStore 实例
  }

  @Provides
  @Singleton
  fun provideAppUserRepository(
    userService: UserService,
    moshi: Moshi,
    dataStore: DataStore<Preferences> // 注入 DataStore 实例
  ): AppUserRepository {
    return AppUserRepositoryImpl(userService, dataStore, moshi) // 创建 AppUserRepositoryImpl 实例
  }

  @Provides
  @Singleton
  fun provideUidFlow(dataStore: DataStore<Preferences>): Flow<String> {
    return dataStore.data.map { preferences ->
      preferences[UID_KEY] ?: ""
    }
  }



}